package com.fcgzs.order.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Auther: ljj
 * @Description:
 */
@Configuration
@EnableResourceServer//开启资源认证
//@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)//开启角色权限设置
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    //声明公钥的路径
    public final static String KEY_PATH = "public.key";

    //读取公钥
    private String getPublicKey() {
        ClassPathResource resource = new ClassPathResource(KEY_PATH);
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            //判断文件中是否有一行数据
            String s;
            if ((s = bufferedReader.readLine()) != null) {
                return s;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    //加载秘钥库tokenStore
    @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter){
        return new JwtTokenStore(jwtAccessTokenConverter);
    }

    //加载JwtAccessTokenConverterJWT令牌转换器
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setVerifierKey(this.getPublicKey());
        return jwtAccessTokenConverter;
    }



    //校验令牌


    //配置放行的请求（不需要认证）
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //.antMatchers("/user/add","/user/load/*")   //放行的请求
                //.permitAll()
                .anyRequest().
                authenticated();    //其他地址需要认证授权
    }


}
